import std/os # 导入 os 库

const c = 10 # 定义常量 c, r 分别存储最大行数与列数
const r = 10
type World = array[c, array[r, int]] # 定义数据类型 World 用于存储世界数据
var myWorld: World # 定义变量 myWorld 实例化 World
myWorld[0][1] = 1 # 初始化世界
myWorld[1][2] = 1
myWorld[2][0] = 1
myWorld[2][1] = 1
myWorld[2][2] = 1

var cmd: string # 定义变量 cmd 用于存储输入
while cmd != "q":
    discard execShellCmd("cls") # 执行命令 cls (仅限 Windows)清屏
    var world = myWorld # 复制变量从 myWorld 到 world
    var output: string # 定义并初始化输出
    for i in countup(0, c - 1):     # 遍历
        for j in countup(0, r - 1):
            var state: int = 0 # 定义 state 记录周围细胞状态（活细胞数量）
            if not (i == 0 or j == 0):                # 进行位置判定，防止索引越界
                state = state + myWorld[i - 1][j - 1]
            if not (i == 0):
                state = state + myWorld[i - 1][j]
            if not (i == 0 or j == r - 1):
                state = state + myWorld[i - 1][j + 1]
            if not (j == 0):
                state = state + myWorld[i][j - 1]
            if not (j == r - 1):
                state = state + myWorld[i][j + 1]
            if not (i == c - 1 or j == 0):
                state = state + myWorld[i + 1][j - 1]
            if not (i == c - 1):
                state = state + myWorld[i + 1][j]
            if not (i == c - 1 or j == r - 1):
                state = state + myWorld[i + 1][j + 1]

            # 游戏核心逻辑
            if state < 2 or state > 3:
                world[i][j] = 0
            elif state == 3:
                world[i][j] = 1

            if world[i][j] == 1:
                output = output & "\e[47m  \e[0m"
            else:
                output = output & "  "
        output = output & "\n"
    echo output
    myWorld = world
    cmd = readLine(stdin)